package cool.houge.pig.infra.controller;

import cool.houge.pig.service.auth.AuthTokenInput;
import cool.houge.pig.service.auth.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 令牌接口.
 *
 * @author KK (kzou227@qq.com)
 */
@Component
public class TokenController {

  private final TokenService tokenService;

  /**
   * 构造对象.
   *
   * @param tokenService 令牌服务
   */
  public TokenController(TokenService tokenService) {
    this.tokenService = tokenService;
  }

  /**
   * @param request
   * @return
   */
  public Mono<ServerResponse> token(ServerRequest request) {
    return request
        .formData()
        .map(this::toAuthTokenInput)
        .flatMap(tokenService::obtainToken)
        .flatMap(ServerResponse.ok()::bodyValue);
  }

  private AuthTokenInput toAuthTokenInput(MultiValueMap<String, String> form) {
    var builder = AuthTokenInput.builder();
    builder
        .grantType(form.getFirst("grant_type"))
        .clientId(form.getFirst("client_id"))
        .clientSecret(form.getFirst("client_secret"))
        .username(form.getFirst("username"))
        .password(form.getFirst("password"))
        .refreshToken(form.getFirst("refresh_token"));
    return builder.build();
  }
}
